package com.youmans.minio.utils;

import com.youmans.minio.config.MinioProp;
import io.minio.MinioClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component
public class MinioUtils {
 
    @Autowired
    private MinioClient client;
    @Autowired
    private MinioProp minioProp;
 
    /**
     * 创建bucket
     *
     * @param bucketName bucket名称
     */
    @SneakyThrows
    public void createBucket(String bucketName) {
        if (!client.bucketExists(bucketName)) {
            client.makeBucket(bucketName);
        }
    }
 
    /**
     * 上传文件
     *
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
    public String uploadFile(MultipartFile file, String bucketName) throws Exception {
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            return null;
        }
        try {
	       	// 判断存储桶是否存在
	        createBucket(bucketName);
	        // 文件名
	        String originalFilename = file.getOriginalFilename();
	        // 新的文件名 = 存储桶名称_时间戳.后缀名
	        String fileName = bucketName + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
	        // 开始上传
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
	        client.putObject(bucketName, format+"/"+fileName, file.getInputStream(), file.getContentType());
	        return minioProp.getEndpoint() + "/" + bucketName + "/"+format+"/" + fileName ;
		}  catch (Exception e) {
            log.error("上传文件失败：{}{}", e.getMessage(),file.getName());
            return null ;
        }
    }
}
 